const app = new getApp();
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
Page({
  data: {
    userInfo: app.globalData.userInfo,
    load: true, //加载提示是否显示
    complete: false, //用户是否已经注册
    userData: false, //用户资料是否填写
    error: false, //与服务器的链接是否产生了错误
    code: null, //获取到的code
    openId: "", //如果是首次登录则有openid
    user: { //存储临时用户信息
      username: "",
      phone: "",
      address: ""
    },
    name: '', //真实姓名
    places: [ //选择宿舍或者教学楼等地点
      {
        text: '宿舍楼',
        value: 1
      },
      {
        text: '教学楼及其它',
        value: 2
      },
    ],
    aPlace: "请选择地点",
    place: -1, //选择地点后的value值

    dormitorys: [ //选择书院
    ],
    aDormitory: "请选择书院",
    dormitory: -1, //选择书院后的value值

    classrooms: [ //选择教室
    ],
    aClassroom: "请选择楼层",
    classroom: -1, //选择楼层后的value值
    aAddress: 0, //区分是教学楼号还是详细地址
    step: false,
    steps: [{
        text: '步骤一',
        desc: '欢迎',
      },
      {
        text: '步骤二',
        desc: '注册登录',
      },
      {
        text: '步骤三',
        desc: '完善信息',
      },
    ],
    active: 0,
  },

  // 设置地点
  setPlace(e) {
    this.setData({
      aPlace: "",
      place: e.detail,
      user: {
        username: this.data.user.username,
        phone: this.data.user.phone,
        address: ""
      },
    })
  },
  //设置宿舍
  setDormitory(e) {
    this.setData({
      aDormitory: "",
      dormitory: e.detail
    })
  },
  //设置楼层
  setClassroom(e) {
    if (e.detail == 0) {
      this.setData({
        aAddress: 2
      });
    } else {
      this.setData({
        aAddress: 1
      });
    }
    this.setData({
      aClassroom: "",
      classroom: e.detail,
    });
  },
  //赋值用户名信息
  usernameName: function (e) {
    this.setData({
      user: {
        username: e.detail,
        phone: this.data.user.phone,
        address: this.data.user.address
      },
    })
  },
  //赋值真实姓名信息
  userName(e) {
    this.setData({
      name: e.detail
    })
  },
  //赋值电话信息
  userPhone: function (e) {
    this.setData({
      errPhone: "",
      user: {
        username: this.data.user.username,
        phone: e.detail,
        address: this.data.user.address
      },
    })
  },
  //赋值地址信息
  userAddress: function (e) {
    this.setData({
      user: {
        username: this.data.user.username,
        phone: this.data.user.phone,
        address: e.detail
      },
    })
  },
  customAlert(message) {
    Dialog.alert({
      message: message,
    }).then(() => {
      // on close
    });
  },
  //提交用户信息,成功跳转到首页
  submit() {
    var that = this.data;
    var buildingId = 0;
    if (that.user.phone.length != 11) {
      this.customAlert("请输入正确的手机号!");
      return;
    }
    if (that.name.length == 0) {
      this.customAlert("请输入真实姓名!");
      return;
    }
    if (that.place == 1) { //选择了宿舍楼
      buildingId = that.dormitory;
    } else if (that.place == 2) { //选择了教学楼
      buildingId = that.classroom;
    } else {
      this.customAlert("请选择地点!");
      return;
    }
    if (buildingId == -1) {
      if (that.place == 1) { //选择了宿舍楼
        this.customAlert("请选择宿舍!");
      } else if (that.place == 2) { //选择了教学楼
        this.customAlert("请选择楼层!");
      }
      return;
    } else {
      if (that.place == 1) { //选择了宿舍楼
        if (that.user.address.length == 0) {
          this.customAlert("请输入正确宿舍号!");
          return;
        }
      } else if (that.place == 2) { //选择了教学楼
        if (that.user.address.length == 0) {
          if (that.aAddress == 1) {
            this.customAlert("请输入正确教学楼号!");
          } else if (that.aAddress == 2) {
            this.customAlert("请输入正确详细地址!");
          }
          return;
        }
      }

      //连接服务器
      var openId = "";
      if (that.openId != "") {
        openId = that.openId;
      } else {
        openId = that.userInfo.openId;
      }
      wx.request({
        url: app.globalData.url + 'setUserData',
        method: "POST",
        data: {
          name: that.name,
          username: that.user.username,
          phone: that.user.phone,
          address: that.user.address,
          openId: openId,
          buildingId: buildingId
        },
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        success(res) {
          if (res.data.state == 1) {
            app.globalData.userInfo=res.data.user;
            wx.redirectTo({
              url: '../index/index',
            })
          } else if (res.data.state == 0) {
            wx.showToast({
              title: '更新资料失败！',
              icon: 'error',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '服务器错误！',
              icon: 'error',
              duration: 2000
            })
          }
        },
        fail(res) {
          wx.showToast({
            title: '服务器错误！',
            icon: 'error',
            duration: 2000
          })
        }
      })
    }
  },
  //服务器出现了错误
  errorServer() {
    var that = this;
    wx.showToast({
      title: '服务器错误！',
      icon: 'error',
      duration: 2000
    })
    that.setData({
      error: true
    })
  },
 
  //向服务器读取building
  getBuilding() {
    var that = this;
    wx.request({
      url: app.globalData.url + 'getBuilding',
      method: "POST",
      data: {
        code: that.data.code
      },
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        if (res.data.state == 1) {
          res.data.building.forEach(function (item) {
            if (item.place == 1) {
              that.data.dormitorys.push({
                text: item.building,
                value: item.id
              });
            } else if (item.place == 2) {
              that.data.classrooms.push({
                text: item.building,
                value: item.id
              });
            }
          });
          that.data.classrooms.push({
            text: '其它',
            value: 0
          });
          that.setData({
            dormitorys: that.data.dormitorys,
            classrooms: that.data.classrooms
          });
        } else {
          that.errorServer(); //服务器发生了错误
        }
      },
      fail(res) {
        that.errorServer(); //服务器发生了错误
      }
    })
  },
  //获取微信上绑定的手机号
  getPhone(e) {
    var that = this;
    var iv = e.detail.iv;
    var encryptedData= e.detail.encryptedData;
    if(iv==encryptedData){
      Dialog.alert({
        message: '您取消了获取！',
      })
      return;
    }
    wx.login({
      success: res => {
        var code = res.code;
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: app.globalData.url + 'getPhone',
          method: "POST",
          data: {
            code: code,
            encryptedData: encryptedData,
            iv: iv,
          },
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          success(res) {
            
            if(res.data.state==1){
              that.setData({
                errPhone: "",
                user: {
                  username: that.data.user.username,
                  phone: res.data.phone,
                  address: that.data.user.address
                },
              })
            }
          }
        })
      }
    });
  },
  onLoad: function (options) {
    var that = this;
    var active=options.active;
    var returnUrl="";
    if(active != null){
      returnUrl="?active="+active;
    }else{
      if(options.norm==1){//添加购物车
        returnUrl="?norm=1&number="+options.number+"&normId="+options.normId+"&product_id="+options.product_id
      }
      if(options.norm==2){//立即购买
        returnUrl="?norm=2&number="+options.number+"&normId="+options.normId+"&product_id="+options.product_id
      }
    }
    //加载页面进行获取登录信息
    wx.login({
      success: res => {
        wx.request({
          url: app.globalData.url + 'getUserOpenId',
          method: "POST",
          data: {
            code: res.code
          },
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          success(res) {
            //已注册，成功登录
            if (res.data.state == 1) {
              app.globalData.userInfo = res.data.user;
              that.setData({
                userInfo: res.data.user,
                user: {
                  username: res.data.user.username,
                  phone: res.data.user.phone,
                  address: res.data.user.address
                }
              })
              //资料还没填写
              if (res.data.user.address == null || res.data.user.address == "") {
                //后台获取宿舍等信息
                that.getBuilding();
                //提示完善资料
                wx.showToast({
                  title: '请完善资料！',
                  icon: 'error',
                  duration: 2000
                })
                that.setData({
                  userData: true,
                  active: 2,
                  load: false, //加载提示是否显示
                })
              } else {
                //信息完整，进入主页
                wx.redirectTo({
                  url: '../index/index'+returnUrl,
                })
                return;
              }
            } else if (res.data.state == 0) {
              //用户没有进行登录注册，提示登录注册
              app.globalData.userInfo = null;
              that.setData({
                step: true,
                openId: res.data.openId,
                load: false, //加载提示是否显示
              })
            } else {
              that.errorServer(); //服务器发生了错误
            }
          },
          fail(res) {
            that.errorServer(); //服务器发生了错误
          }
        })
      }
    })
  },
  step() {
    this.setData({
      step: false,
      complete: true,
      active: 1
    })
  },
  //首次打开微信小程序进行登录
  getUserProfile(e) {
    var that = this;
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        wx.request({
          url: app.globalData.url + 'setUser',
          method: "POST",
          data: {
            openId: that.data.openId,
            username: res.userInfo.nickName
          },
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          success(res) {
            if (res.data.state == 1) {
              //注册成功
              app.globalData.userInfo = res.data;
              that.setData({
                userInfo: res.data,
                complete: false, //注册完成后隐藏登录
                active: 2,
                userData: true, //注册完成后显示填写资料
                user: {
                  username: res.data.username,
                  phone: that.data.user.phone,
                  address: that.data.user.address
                },
              });
              //后台获取宿舍等信息
              that.getBuilding();
            } else {
              //注册失败
            }
          },
          fail(res) {
            that.errorServer(); //服务器发生了错误
          }
        })
      }
    })
  },
})